package org.icec.web.core.sys.controller;

import java.awt.Font;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.icec.common.annotion.BussinessLog;
import org.icec.common.base.tips.DataTip;
import org.icec.common.base.tips.ErrorTip;
import org.icec.common.base.tips.Tip;
import org.icec.common.constants.SessionConstants;
import org.icec.common.utils.AjaxUtils;
import org.icec.common.web.BaseController;
import org.icec.web.core.shiro.exception.IncorrectCaptchaException;
import org.icec.web.core.shiro.jwt.JwtUtil;
import org.icec.web.core.sys.model.SysGlobal;
import org.icec.web.core.sys.model.SysUser;
import org.icec.web.core.sys.service.SysGlobalService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;

@Controller
public class SystemCtrl extends BaseController {
	private static final Logger log = LoggerFactory.getLogger(SystemCtrl.class);
	@Autowired
	private SysGlobalService sysGlobalService;
	@Autowired
	private JwtUtil jwtUtil;

	@BussinessLog(value = "生成验证码")
	@RequestMapping("kaptcha.jpg")
	public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 设置请求头为输出图片类型
		response.setContentType("image/gif");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		// 三个参数分别为宽、高、位数
		SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
		// 设置字体
		specCaptcha.setFont(new Font("Verdana", Font.PLAIN, 32)); // 有默认字体，可以不用设置
		// 设置类型，纯数字、纯字母、字母数字混合
		specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER);

		// 验证码存入session
		request.getSession().setAttribute(SessionConstants.KAPTCHA_SESSION_KEY, specCaptcha.text().toLowerCase());

		// 输出图片流
		specCaptcha.out(response.getOutputStream());

	}

	@GetMapping("sys/login")
	public String login(@ModelAttribute("msg") String msg, ModelMap model) {

		model.addAttribute("msg", msg);
		SysGlobal global = sysGlobalService.getGlobal();
		model.addAttribute("global", global);
		return "sys/login";
	}

	@PostMapping("sys/login")
	public String dologin(HttpServletRequest request, HttpServletResponse response, RedirectAttributes model) {
		if (SecurityUtils.getSubject().isAuthenticated()) {
			SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
			log.info("登入成功" + user.getName());
			if (AjaxUtils.isAjaxRequest(request)) {
				String token = jwtUtil.generateToken(user);
				DataTip succ = new DataTip(token);
				AjaxUtils.writeJson(succ, response);
				return null;
			} else {
				return "redirect:/";
			}
		} else {
			log.info("登入失败");

			if (AjaxUtils.isAjaxRequest(request)) {
				ErrorTip error = new ErrorTip("登录失败");
				AjaxUtils.writeJson(error, response);
				return null;
			}
			String exception = (String) request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
			// String message =
			// (String)request.getAttribute(FormAuthenticationFilter.DEFAULT_MESSAGE_PARAM);
			if (IncorrectCaptchaException.class.getName().equals(exception)) {
				model.addFlashAttribute("msg", "验证码错误");
			} else if (LockedAccountException.class.getName().equals(exception)) {
				model.addFlashAttribute("msg", "账户已冻结");
			} else {
				model.addFlashAttribute("msg", "用户名或密码错误");
			}
			return "redirect:/sys/login";
		}

	}

	/**
	 * 刷新token
	 * 
	 * @return
	 */
	@RequestMapping("/refresh")
	@ResponseBody
	public Tip refresh(HttpServletRequest request) {
		SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
		String token = jwtUtil.generateToken(user);
		return data(token);
	}

	@GetMapping("sys/logout")
	public String logout() {
		SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
		log.info("登出:" + user.getLoginName());
		SecurityUtils.getSubject().logout();
		return "redirect:/sys/login";
	}
}
